package cn.itsource.org.service.impl;

import cn.itsource.config.MailSendComponent;
import cn.itsource.org.domain.TEmployee;
import cn.itsource.user.domain.TLogininfo;
import cn.itsource.org.domain.TShop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.query.ShopQuery;
import cn.itsource.org.service.IShopService;
import cn.itsource.utils.AjaxResult;
import cn.itsource.utils.MD5;
import cn.itsource.utils.PageList;
import cn.itsource.vo.ShopVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ShopServiceImpl implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public PageList<TShop> findPageByParam(ShopQuery query) {
        PageList<TShop> pageList = new PageList<>();
        if (query.getKeyword() != null && !"".equals(query.getKeyword())) {//keyword = "       "
            query.setKeyword(query.getKeyword().trim());
        }
        //根据条件查询当前查询页列表数据
        List<TShop> shopList = shopMapper.findPageByParam(query);
        Long count = shopMapper.findPageByParamCount(query);

        pageList.setTotal(count);
        pageList.setData(shopList);

        return pageList;
    }

    @Override
    public AjaxResult settlement(ShopVo vo) {
        //注意：目前，我们需要将所有的验证放在数据库操作之前
        //1.员工的用户名、手机号、邮箱不能为空
        if (StringUtils.isAnyBlank(vo.getShop().getName(),vo.getEmployee().getUsername(),vo.getEmployee().getPhone(),vo.getEmployee().getEmail())){
            return AjaxResult.me().setSuccess(false).setMessage("店铺名或用户名、手机号或邮箱不能为空");
        }
        //2.判断添加的员工，它的用户名、手机号和邮箱不能重复
        int count = employeeMapper.checkUsernameOrEmailOrPhoneIsExits(vo.getEmployee().getUsername(), vo.getEmployee().getPhone(), vo.getEmployee().getEmail());
        if (count > 0) {//如果大于0，则说明重复
            return AjaxResult.me().setSuccess(false).setMessage("用户名、手机号或邮箱不能重复");
        }
        //3. 店铺名不能为空且不能重复
        int shopCount = shopMapper.checkNameIsExits(vo.getShop().getName());
        if (shopCount > 0) {//大于0，说明重复
            return AjaxResult.me().setSuccess(false).setMessage("店铺名称不能重复");
        }
        //添加员工前，要字段进行初始化值
        vo.getEmployee().setState(TEmployee.STATE_QIYONG);
        //给员工添加的密码进行加密处理
        vo.getEmployee().setPassword(MD5.getMD5(vo.getEmployee().getPassword()));
        //1.将管理员的信息保存到 员工表（要先新增员工，再添加店铺。两点：店铺添加时，要绑定员工的id）
        employeeMapper.save(vo.getEmployee());
        //2.将店铺的信息保存到店铺表
        //将新增的员工的自增长主键，赋值给店铺的admin_id
        vo.getShop().setAdminId(vo.getEmployee().getId());
        //添加初始化值
        vo.getShop().setRegisterTime(new Date());
        //新增的店铺，状态默认为 【审核中=0】
        vo.getShop().setState(TShop.STATE_DAISHENGHE);//直接写0L，在程序开发中，称为 魔法数字
        shopMapper.save(vo.getShop());

        //2021年6月23日：同时添加一条数据到t_logininfo表
        TLogininfo logininfo = new TLogininfo();
        logininfo.setUsername(vo.getEmployee().getUsername());
        logininfo.setEmail(vo.getEmployee().getEmail());
        logininfo.setPassword(vo.getEmployee().getPassword());
        logininfo.setPhone(vo.getEmployee().getPhone());
        logininfo.setDisable(true);
        logininfo.setType(true);
        logininfo.setLoginId(vo.getEmployee().getId());
        logininfoMapper.insertSelective(logininfo);
        return AjaxResult.me();
    }


    @Autowired
    private MailSendComponent mailSendComponent;

    @Override
    public AjaxResult shenghe(Long id, Integer state) {
        //添加校验
        if (id == null || state == null) {
            return AjaxResult.me().setSuccess(false).setMessage("缺少必传参数");
        }

        //1. 修改t_shop表的状态字段
        shopMapper.updateStateById(id,state);
        //2. 发邮件（在这里，主要是发送通知，告知店铺管理员，当前店铺的入驻申请结果 -----> 文本）
        //2.0 先根据店铺ID查询店铺信息
        TShop shop = shopMapper.findShopById(id);
        //2.1 先根据店铺ID查询对应的管理员信息
        TEmployee employee = employeeMapper.findById(shop.getAdminId());
        //2.2 从管理员信息中，获取邮件地址
        String email = employee.getEmail();

        if (StringUtils.isNotBlank(email)) {
            //2.3 根据邮件地址，调用发送工具类，发送邮件
            String mailContent = "";
            if (state.longValue() == TShop.STATE_ZHENGCHANG) {
                mailContent="恭喜，店铺审核通过";
            }else if (state.longValue() == TShop.STATE_GUANBI){
                mailContent="sorry，店铺被禁用！";
            }
            mailSendComponent.sendSimpleMail(email,"店铺审核通知",mailContent);
        }
        return AjaxResult.me();
    }
}
